package de.home.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Utils {

   public static String getLocalSubnetMask() throws Exception {
      InetAddress localHost = Inet4Address.getLocalHost();
      NetworkInterface networkInterface = NetworkInterface.getByInetAddress(localHost);
      short prefixLength = networkInterface.getInterfaceAddresses().get(0).getNetworkPrefixLength();
      StringBuilder mask = new StringBuilder(32);

      for (int i = 0; i < prefixLength; i++) {
         mask.append("1");
      }

      int subInt = Integer.parseInt(mask.toString(), 2);

      ByteBuffer buffer = ByteBuffer.allocate(32);
      buffer.order(ByteOrder.LITTLE_ENDIAN);
      buffer.putInt(subInt);
      buffer.position(0);
      byte[] bytes = new byte[4];
      buffer.get(bytes);
      return InetAddress.getByAddress(bytes).getHostAddress();
   }
}
